import sys, os
from optparse import OptionParser
import csv
from report_server import run_server
from model import Node, connection
import sqlite3

def run_report(rootdir, setid):
    nodes = list(connection.Node.find({'setid':str(setid)}))
    tup_nodes = [(x['path'],x['filename']) for x in nodes]
    conn = sqlite3.connect(':memory:')
    with conn:
        cur = conn.cursor()
        cur.execute("CREATE TABLE nodes(path TEXT, filename TEXT)")
        cur.executemany("INSERT INTO nodes VALUES(?,?)", tup_nodes)

        tup_walk = [(os.path.relpath(root), os.path.basename(f)) for root, dirs, files in os.walk(rootdir, topdown=True, followlinks=True) for f in files]

        cur.executemany("DELETE FROM nodes WHERE path=? AND filename=?", tup_nodes)

        with open('dump.sql', 'w') as fdump:
            for line in conn.iterdump():
                fdump.write("%s\n" %line)
    

if __name__ == '__main__':
    usage = "usage: %prog [options] rootdir"
    outfilename = "out.csv"
    parser = OptionParser()
    parser.add_option("-s", "--setid", action="store", type="string", dest="setid", default=None, help="setid")
    parser.add_option("-p", "--http-port", action="store", type="int", dest="port", default=None, help="run http server on port(PORT)", metavar="PORT")

    (options, args) = parser.parse_args()
    if len(args) == 0:
        parser.error("need root dir")

    rootdir = args[0]

    if not os.path.exists('out.csv'):
        run_report(rootdir, options.setid)             
        
    if options.port != None:
        run_server(options.port)
